<?php

// 引入函数库
include_once("./config/config.php");

//判断是否已登录
if (isset($_COOKIE['admin'])) {

    $admin = LoginCheck(false);

    if ($admin) {
        notice('您已登录，无须重复登录');
    }
}

//登录,验证保存数据
if ($_POST) {
    // 获取页面的提交数据
    $username = isset($_POST['username']) ? trim($_POST['username']) : '';
    $password = isset($_POST['password']) ? trim($_POST['password']) : '';
    $code = isset($_POST['code']) ? trim($_POST['code']) : '';

    // 数据验证
    if (empty($username)) {
        notice("用户名不能为空！");
    }
    if (empty($password)) {
        notice("密码不能为空！");
    }
    if (empty($code)) {
        notice("验证码不能为空！");
    }
    if ($code != $_SESSION['code']) {
        notice("验证码错误！");
    }

    // 获取该用户在admin表的所有信息
    $sql = "SELECT * FROM `pre_admin` WHERE `username` = '$username'";
    $admin = find($sql);

    //验证用户存在
    if (empty($admin)) {
        notice("用户名不存在");
    }

    // 数据库的密码是进行加密过的，因此这里也给登录密码进行同样的加密
    $password = md5($password . $admin['salt']);

    //验证密码正确
    if ($admin['password'] != $password) {
        notice("密码错误");
    }

    // 删除密码和密码盐
    unset($admin['password']);
    unset($admin['salt']);

    // 存储登录信息
    setcookie('admin', json_encode($admin));
    // $_SESSION['admin'] = $admin;

    notice('登录成功', 'index.php');
}

//开启会话
// session_start();
?>


<!DOCTYPE html>
<html lang="en">

<head>

    <!-- 引入meta设置 -->
    <?php include_once("common/meta.php") ?>

</head>

<body>

    <div class="navbar">
        <div class="navbar-inner">
            <a class="brand" href="index.php"><span class="second">Admin</span></a>
        </div>
    </div>

    <div class="row-fluid">
        <div class="dialog">
            <div class="block">
                <p class="block-heading">登录</p>
                <div class="block-body">
                    <form method="post">
                        <label>用户名</label>
                        <input type="text" name="username" class="span12" placeholder="请输出用户名">
                        <label>密码</label>
                        <input type="password" name="password" class="span12" placeholder="请输出密码">
                        <label>验证码</label>
                        <input type="text" name="code" class="span8" placeholder="请输出验证码">
                        <img src=" /config/imgcode.php" onclick="this.src='/config/imgcode.php?id=' + Math.random()" class="span4">
                        <button class="btn btn-primary pull-right">登录</button>
                        <div class="clearfix"></div>
                    </form>
                </div>
            </div>
        </div>
    </div>

</body>

</html>